package com.gupao.edu.bio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * @description：阻塞式I/O创建的客户端
 * @author：huabin.lin@sfwl.com.cn
 * @version：2018年11月01日 15:31
 */
public class BioClient {

    /***
     * 默认的端口号
     */
    private static int DEFAULT_SERVER_PORT = 8888;

    /***
     * 默认的IP地址
     */
    private static String DEFAULT_SERVER_IP = "127.0.0.1";

    /***
     * 发送信息
     * @param expression
     * @throws Exception
     */
    public static void send(String expression) {
        send(DEFAULT_SERVER_PORT, expression);
    }

    /***
     * 发送信息
     * @param port
     * @param expression
     * @throws Exception
     */
    public static void send(int port, String expression) {
        System.out.println("算术表达式：" + expression);
        Socket socket = null;

        BufferedReader in = null;

        PrintWriter out = null;

        try {
            socket = new Socket(DEFAULT_SERVER_IP, port);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            // 若 autoFlush = false，则会出现服务端无法读取数据，从而导致阻塞
            out = new PrintWriter(socket.getOutputStream(), true);
            out.println(expression);
            System.out.println("结果为：" + in.readLine());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != in) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                in = null;
            }

            if (null != out) {
                out.close();
                out = null;
            }

            if (null != socket) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                socket = null;
            }
        }
    }
}
